package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.Object.StockBalance;
import Com.Ring.TradingMobile.Service.WebService;
import android.R.integer;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class SoDuCKActivity extends Activity {

	/*
	 * Declare Variable
	 */
	private Button btn_Buy;
	private Button btn_Sell;
	private Button btn_CashBalance;
	private Button btn_Back;
	private Button btn_Home;
	private TextView lblGainLoss;
	private LinearLayout layout_Header;
	private LinearLayout layout_Content;
	private TextView lblAccountTextView;

	private int[] StrHeaderId = new int[] { R.string.strMaCK,
			R.string.str_Total, R.string.str_MoneyAvailability,
			R.string.str_T1, R.string.str_T2, R.string.str_T3,
			R.string.str_PriceAvg, R.string.str_PriceMarket,
			R.string.str_GrainLoss };

	private String TAG = "SoDuCKActivityLog";
	private StockBalanceAsyncTask stockBalanceAsyncTask;
	private static final int DIALOG_LOADING = 0;
	private String StrGrainLoss = "";

	/*
	 * Auto Generation
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.soduchungkhoan);
		InitControlId();
		Log.d(TAG, "OnCreate");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d(TAG, "OnPause");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		Log.d(TAG, "OnRestart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d(TAG, "OnResume");
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "OnStart");
		lblGainLoss.setText("");
		showDialog(DIALOG_LOADING);
		LoadStockBalancesAsync();
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "OnStop");
		CancelLoadStockBalancesAsync();
	}

	/*
	 * Writer by Huu_Nhan
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOADING: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("Loading...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	private void CancelLoadStockBalancesAsync() {
		if (stockBalanceAsyncTask != null) {
			try {
				stockBalanceAsyncTask.cancel(true);
				stockBalanceAsyncTask = null;
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}
		}
	}

	private void LoadStockBalancesAsync() {
		CancelLoadStockBalancesAsync();
		stockBalanceAsyncTask = new StockBalanceAsyncTask();
		stockBalanceAsyncTask.execute(Session.subCustAccounts.get(0));
	}

	private void InitControlId() {
		btn_Back = (Button) findViewById(R.id.btnBack);
		btn_Buy = (Button) findViewById(R.id.btn_Mua);
		btn_CashBalance = (Button) findViewById(R.id.btn_SoDuTien);
		btn_Home = (Button) findViewById(R.id.btnHome);
		btn_Sell = (Button) findViewById(R.id.btn_Ban);
		lblGainLoss = (TextView) findViewById(R.id.lblGainLoss);

		layout_Header = (LinearLayout) findViewById(R.id.linearHeader);
		layout_Content = (LinearLayout) findViewById(R.id.linearContent);
		lblAccountTextView = (TextView) findViewById(R.id.lblTaiKhoan);
		lblAccountTextView.setText("TK: " + Session.subCustAccounts.get(0));

		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(30);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources()
					.getColor(R.color.title_row));
			rowsHeader[i].addView(txtHeader[i]);

			rowsHeader[i].setPadding(5, 1, 1, 1);
			tableHeader.addView(rowsHeader[i]);
		}
		tableHeader.setPadding(0, 10, 0, 10);
		layout_Header.addView(tableHeader);

		InitControlListen();

	}

	private void InitControlListen() {
		btn_CashBalance.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						SoDuTienActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Home.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						TradingMobileLoggedActivity.class);
				startActivity(intent);
				finish();
				onDestroy();
			}
		});
		btn_Back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
				onDestroy();
			}
		});
		btn_Buy.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), MuaActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_Sell.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), BanActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}

	private void ShowViewStockBalances(List<StockBalance> listStockBalance) {
		try {
			if (listStockBalance != null && listStockBalance.size() > 0) {
				layout_Content.removeAllViewsInLayout();
				String text = null;
				int xColor = R.color.whiles;
				for (StockBalance balances : listStockBalance) {
					TableLayout tableContent = new TableLayout(
							SoDuCKActivity.this);
					TableRow[] rowContents = new TableRow[StrHeaderId.length];
					TextView[] txtContent = new TextView[StrHeaderId.length];
					for (int i = 0; i < txtContent.length; i++) {
						rowContents[i] = new TableRow(SoDuCKActivity.this);
						txtContent[i] = new TextView(SoDuCKActivity.this);
						xColor = R.color.whiles;
						// set text
						switch (i) {
						case 0:
							text = balances.Symbol;
							xColor = balances.color;
							break;
						case 1:
							text = Common.FormatNumber(Double.parseDouble(balances.Total));
							break;
						case 2:
							text = Common.FormatNumber(Double.parseDouble(balances.Availability));
							break;
						case 3:
							text = balances.T1;
							break;
						case 4:
							text = balances.T2;
							break;
						case 5:
							text = balances.T3;
							break;
						case 6:
							text = balances.Average;
							break;
						case 7:
							text = Common.FormatNumber(Double.parseDouble(balances.MarketPrice));
							xColor = balances.color;
							break;
						case 8:
							text = Common.FormatShortNumber(Double.parseDouble(balances.ProfitAndLoss));
							xColor = balances.colorGainLoss;
							break;

						}
						txtContent[i].setText(text);

						txtContent[i].setTextColor(getResources().getColor(
								xColor));
						txtContent[i].setHeight(30);
						txtContent[i].setTextSize(12);
						txtContent[i].setGravity(Gravity.RIGHT);
						txtContent[i].setPadding(0, 0, 2, 0);
						LayoutParams layout = new LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT);
						// layout.width = 50;
						// txtContent[i].setLayoutParams(layout);

						txtContent[i]
								.setBackgroundResource(R.drawable.border_color_textview);
						rowContents[i].addView(txtContent[i], layout);
						rowContents[i].setPadding(1, 1, 1, 1);
						tableContent.addView(rowContents[i]);
					}
					tableContent.setPadding(0, 10, 0, 10);
					layout_Content.addView(tableContent);
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private List<StockBalance> GetStockBalance(String subAccount) {
		List<StockBalance> listData = new ArrayList<StockBalance>();
		int accountType = Common.ACCOUNT.GetAccountType(subAccount);
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetPortfolio);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(subAccount);
		parAccountNo.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPageNumber = new PropertyInfo();
		parPageNumber.setName("pageNumber");
		parPageNumber.setValue(1);
		parPageNumber.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPageSize = new PropertyInfo();
		parPageSize.setName("pageSize");
		parPageSize.setValue(integer.config_shortAnimTime);
		parPageSize.setNamespace(WebService.NAMESPACE);

		PropertyInfo parAccountType = new PropertyInfo();
		parAccountType.setName("accountType");
		parAccountType.setValue(accountType);
		parAccountType.setNamespace(WebService.NAMESPACE);

		PropertyInfo parIsFirstTime = new PropertyInfo();
		parIsFirstTime.setName("isFirstTime");
		parIsFirstTime.setValue(Session.isFirstTime);
		Session.isFirstTime = true;
		parIsFirstTime.setNamespace(WebService.NAMESPACE);

		PropertyInfo parPosition = new PropertyInfo();
		parPosition.setName("position");
		parPosition.setValue(1);
		parPosition.setNamespace(WebService.NAMESPACE);

		request.addProperty(parAccountNo);
		request.addProperty(parPageNumber);
		request.addProperty(parPageSize);
		request.addProperty(parAccountType);
		request.addProperty(parIsFirstTime);
		request.addProperty(parPosition);

		envelope.setOutputSoapObject(request);
		HttpTransportSE http = new HttpTransportSE(
				WebService.ADDRESS_ETRADE_SERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetPortfolio;

		try {
			LinkedList<HeaderProperty> getSession = Session.GetSession();
			List<HeaderProperty> respHeaders = http.call(soapAction, envelope,
					getSession);
			if (respHeaders != null) {
				Session.SetSession(respHeaders);
			} else
				return listData;
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {

					StrGrainLoss = resultsObj.getJSONObject("Result")
							.getJSONObject("SumInPage").getString("GainLoss");

					JSONArray stockBalances = resultsObj
							.getJSONObject("Result").getJSONArray("Data");
					for (int i = 0; i < stockBalances.length(); i++) {
						JSONObject jsonObject = stockBalances.getJSONObject(i);
						StockBalance balances = new StockBalance();
						balances.Symbol = jsonObject
								.getString(StockBalance.PropertyString.Symbol
										.toString());
						balances.Total = jsonObject
								.getString(StockBalance.PropertyString.Total
										.toString());
						balances.Availability = jsonObject
								.getString(StockBalance.PropertyString.SellableShare
										.toString());
						balances.T1 = jsonObject
								.getString(StockBalance.PropertyString.WTR_T1
										.toString());
						balances.T2 = jsonObject
								.getString(StockBalance.PropertyString.WTR_T2
										.toString());
						balances.T3 = jsonObject
								.getString(StockBalance.PropertyString.WTR_T3
										.toString());
						balances.Average = jsonObject
								.getString(StockBalance.PropertyString.AvgPrice
										.toString());
						balances.MarketPrice = jsonObject
								.getString(StockBalance.PropertyString.MarketPrice
										.toString());
						balances.ProfitAndLoss = jsonObject
								.getString(StockBalance.PropertyString.GainLoss
										.toString());
						double marketPrice = jsonObject
								.getDouble(StockBalance.PropertyString.MarketPrice
										.toString());
						double refPrice = jsonObject
								.getDouble(StockBalance.PropertyString.RefPrice
										.toString());
						double gainLossObj = jsonObject
								.getDouble(StockBalance.PropertyString.GainLoss
										.toString());
						if (marketPrice > refPrice) {
							balances.color = R.color.up;
						} else if (marketPrice < refPrice) {
							balances.color = R.color.down;
						} else {
							balances.color = R.color.nochange;
						}
						if (gainLossObj > 0) {
							balances.colorGainLoss = R.color.up;
						} else if (gainLossObj < 0) {
							balances.colorGainLoss = R.color.down;
						} else {
							balances.colorGainLoss = R.color.nochange;
						}
						listData.add(balances);
					}
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		return listData;
	}

	private class StockBalanceAsyncTask extends
			AsyncTask<String, Void, List<StockBalance>> {

		@Override
		protected List<StockBalance> doInBackground(String... params) {
			List<StockBalance> listStockBalance = GetStockBalance(params[0]);
			return listStockBalance;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<StockBalance> result) {
			ShowViewStockBalances(result);
			if (StrGrainLoss != "") {
				lblGainLoss.setText(Common.FormatNumber(Double.parseDouble(StrGrainLoss))+" VND");
				double gainLossDouble = Double.parseDouble(StrGrainLoss);
				if (gainLossDouble > 0) {
					lblGainLoss.setTextColor(getResources()
							.getColor(R.color.up));
				} else if (gainLossDouble < 0) {
					lblGainLoss.setTextColor(getResources().getColor(
							R.color.down));
				} else {
					lblGainLoss.setTextColor(getResources().getColor(
							R.color.nochange));
				}
			}
			StrGrainLoss = "";
			removeDialog(DIALOG_LOADING);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}
}
